package com.freightoa.foundation.presentation.domain

import com.freightoa.foundation.net.ApiResult
import com.freightoa.foundation.net.bean.SGLResponse


abstract class BaseUseCase {
    fun <T> handleTask(apiResult: ApiResult<SGLResponse<T>>?): Result<T?> {
        if (apiResult == null) {
            return Result.failure(NullPointerException("data is null"))
        }
        return when (apiResult) {
            is ApiResult.Success -> Result.success(apiResult.data.data)
            is ApiResult.Error -> Result.failure(RuntimeException(apiResult.message))
            is ApiResult.Exception -> Result.failure(apiResult.throwable)
        }
    }

    fun <T> handleNoDataTask(apiResult: ApiResult<SGLResponse<T>>?): Result<T?> {
        if (apiResult == null) {
            return Result.failure(NullPointerException("data is null"))
        }
        return when (apiResult) {
            is ApiResult.Success -> processSuccessResult(apiResult)
            is ApiResult.Error -> Result.failure(RuntimeException(apiResult.message))
            is ApiResult.Exception -> Result.failure(apiResult.throwable)
        }
    }

    fun <T> handleSuccessDataTask(apiResult: ApiResult<SGLResponse<T>>?): Result<SGLResponse<T>> {
        if (apiResult == null) {
            return Result.failure(NullPointerException("data is null"))
        }
        return when (apiResult) {
            is ApiResult.Success -> {
                return Result.success(apiResult.data)
            }

            is ApiResult.Error -> Result.failure(RuntimeException(apiResult.message))
            is ApiResult.Exception -> Result.failure(apiResult.throwable)
        }
    }

    private fun <T> processSuccessResult(result: ApiResult.Success<SGLResponse<T>>): Result<T> {
        // 获取数据
        val data =
            result.data.data ?: return Result.failure(NullPointerException(result.data.message_en))
        return Result.success(data)
    }

}